# a category for incidents. supports hierarchies. should probably change this to a tagging setup.
class Category < ActiveRecord::Base
  belongs_to(:parent, :class_name => "Category")
  has_many(:children, :foreign_key => "parent_id", :class_name => "Category")
  
  # before destroy check for stuff
  before_destroy(:check_dependencies)

  # options for select tag
  def self.select_options(target = nil)
    all.collect{|c| c == target ? nil : [c.full_name, c.id]}.compact
  end
  
  # name with parent and number
  def full_name
    fn = name || ""
    p = parent
    loop { break if p.nil?; fn = p.name + " > " + fn; p = p.parent }
    id.to_s + ". " + fn
  end
  
  protected
    def check_dependencies
      raise "Category has incidents in it." if Incident.find_by_category_id(self.id)
      raise "Category is a parent to other categories." unless children.empty?
    end
end
